package com.xyoto.community.service.impl;

import com.xyoto.community.constant.AuthenticationStatus;
import com.xyoto.community.constant.OperationStatus;
import com.xyoto.community.dto.StudentAuthenticationDTO;
import com.xyoto.community.entity.main.StudentAuthentication;
import com.xyoto.community.enums.StudentAuthenticationEnum;
import com.xyoto.community.exception.ExceptionUtils;
import com.xyoto.community.mapper.main.StudentAuthenticationMapper;
import com.xyoto.community.service.StudentAuthenticationService;
import com.xyoto.community.utils.JwtUtils;
import com.xyoto.community.utils.Result;
import com.xyoto.community.utils.XYOtoOssUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author lin
 * @Date 2021/10/20 8:05
 */
@Service
public class StudentAuthenticationServiceImpl implements StudentAuthenticationService {

    @Resource
    private StudentAuthenticationMapper studentAuthenticationMapper;
    @Resource
    private HttpServletRequest request;

    /**
     * 学生认证
     * @param dto 学生认证对象
     * @return
     */
    @Override
    public Result saveStudentAuthentication(StudentAuthenticationDTO dto,MultipartFile file) throws IOException {
        if (null == file){
            ExceptionUtils.error(StudentAuthenticationEnum.CHOICE_PICTURE);
        }
        Integer userId = JwtUtils.getMemberIdByJwtToken(request);
        StudentAuthentication student = new StudentAuthentication();
        BeanUtils.copyProperties(dto,student);
        //保存用户id
        student.setUserId(userId);
        //保存图片路径
        String path = new XYOtoOssUtils().uploadFileAvatar(file, "user");
        if (null == path){
            ExceptionUtils.error(StudentAuthenticationEnum.PICTURE_UPLOAD_FAILED);
        }
        student.setPath(path);
        //保存认证状态
        student.setStatus(AuthenticationStatus.APPROVING);
        Integer save = studentAuthenticationMapper.saveStudentAuthentication(student);
        if (save != OperationStatus.SUCCESS){
            ExceptionUtils.error(StudentAuthenticationEnum.STUDENT_AUTHENTICATION_FAILED);
        }
        return Result.success();
    }
}

   